package org.zuel.innovative.power;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;

@Service
public class TicketServer {

    @Autowired
    private RedisTemplate redisTemplate;
    public LoginTicket findLoginTicket(String ticket) {
        String redisKey="power:ticket:"+ticket;
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }
    public LoginTicket setLoginTicket(Integer userid, HttpServletResponse response){
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(userid);
        loginTicket.setTicket(UUID.randomUUID().toString().replaceAll("-", "")); // 随机凭证
        loginTicket.setStatus(0); // 设置凭证状态为有效（当用户登出的时候，设置凭证状态为无效）
        loginTicket.setExpired(new Date(System.currentTimeMillis() + 1 * 1000)); // 设置凭证到期时间

        // 将登录凭证存入 redis
        String redisKey = "power:ticket:"+loginTicket.getTicket();
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        //head形式加入
        response.addHeader("ticket",loginTicket.getTicket());
//        cookies加入
//             浏览器通过 cookie 存储 ticket
//            Cookie cookie = new Cookie("ticket", loginTicket.getTicket());
//            cookie.setMaxAge(expiredSeconds);
//            cookie.setPath("/");
//            cookie.setHttpOnly(false);
//            cookie.setDomain("xxxxxxxx");
//        response.addCookie(cookie);
        return loginTicket;
    }
}
